package errcode

import (
	"fmt"
	"git.myscrm.cn/golang/common/ykerrcode"
	"net/http"
)

type baseError struct {
	errorCode int32
	errorMsg  string
}

// NewBaseError 构造函数
func NewBaseError(errorCode int32, errorMsg string) error {
	return &baseError{
		errorCode: errorCode,
		errorMsg:  errorMsg,
	}
}

func (e *baseError) Error() string {
	return fmt.Sprintf("ErrorCode:%d, ErrorMsg: %s", e.errorCode, e.errorMsg)
}

func (e *baseError) getErrorCode() int32 {
	return e.errorCode
}

func (e *baseError) getErrorMsg() string {
	return e.errorMsg
}

// ErrorToBaseError 断言错误类型
func ErrorToBaseError(err error) (int32, string) {
	e, ok := err.(*baseError)
	if ok {
		return e.getErrorCode(), e.getErrorMsg()
	}

	return ykerrcode.FAIL, err.Error()
}

// CTogRPCError grpc响应错误类型
func CTogRPCError(err error) error {
	code, str := ErrorToBaseError(err)
	ykErr := ykerrcode.NewErrorCode(int(code), http.StatusOK)
	return ykerrcode.TogRPCError(ykErr, str)
}

const (
	BASE_ORG_BASE                = 30010000
	BASE_ORG_NOT_EXIST           = 30010001
	BASE_ORG_HAVE_USER           = 30010002
	BASE_ORG_HAVE_SUB_DEPARTMENT = 30010003
	BASE_ORG_NAME_EXIST          = 30010004
	BASE_ORG_PARENT_NOT_EXIST    = 30010005

	BASE_ROLE_BASE       = 30020000
	BASE_ROLE_NAME_EXIST = 30020001
	BASE_ROLE_DATA_EXIST = 30020002

	BASE_USER_BASE                = 30030000
	BASE_MOBILE_EXIST             = 30030001
	BASE_USER_NOT_EXIST           = 30030002
	BASE_USER_PASSWD_INVALID      = 30030003
	BASE_USER_NOT_ALLOW_DELETE    = 30030004
	BASE_USER_NOT_ALLOW_FORBIDDEN = 30030005
)

var (
	OrgDataNotExist       = NewBaseError(BASE_ORG_NOT_EXIST, "部门不存在")
	OrgDataHaveUser       = NewBaseError(BASE_ORG_HAVE_USER, "部门下还有员工")
	OrgDataHaveDepartment = NewBaseError(BASE_ORG_HAVE_SUB_DEPARTMENT, "部门下还有子部门")

	OrgNameExist      = NewBaseError(BASE_ORG_NAME_EXIST, "部门名称已存在")
	OrgIdNotExist     = NewBaseError(BASE_ORG_NAME_EXIST, "部门id不存在")
	OrgParentNotExist = NewBaseError(BASE_ORG_PARENT_NOT_EXIST, "上级组织不存在")
)

var (
	RoleNameExist    = NewBaseError(BASE_ROLE_NAME_EXIST, "角色名称已存在")
	RoleUsingErr     = NewBaseError(BASE_ROLE_NAME_EXIST, "角色在使用中")
	RoleDataNotExist = NewBaseError(BASE_ROLE_DATA_EXIST, "角色不存在")
)

var (
	UserMobileExist        = NewBaseError(BASE_MOBILE_EXIST, "手机号已存在")
	UserNotExist           = NewBaseError(BASE_USER_NOT_EXIST, "账号不存在")
	UserPasswdInvalid      = NewBaseError(BASE_USER_PASSWD_INVALID, "密码非法")
	NotAllowDelAdmin       = NewBaseError(BASE_USER_NOT_ALLOW_DELETE, "无法删除管理员账号")
	NotAllowForbiddenAdmin = NewBaseError(BASE_USER_NOT_ALLOW_FORBIDDEN, "无法禁用管理员账号")
)
